#include <stdio.h>
#include "rijndael.h"

#include <QtCore>

int encrypt(QString srcFile, QString dstFile, QString pwd)
{
	unsigned long rk[RKLENGTH(256)];
	unsigned char key[KEYLENGTH(256)];
	uint i;
	int nrounds;

	QByteArray pwdd= QCryptographicHash::hash(pwd.toUtf8(),QCryptographicHash::Md5);
	for (i = 0; i < sizeof(key); i++) key[i] = i<(uint)pwdd.size()?pwdd.at(i):0;

	QFile src(srcFile);
	if(!src.open(QIODevice::ReadOnly)) return 1;

	QFile dst(dstFile);
	if(!dst.open(QIODevice::WriteOnly)){
		src.close();
		return 1;
	}
	int rem= src.size()%16;
	dst.putChar((char)(rem==0?0:16-rem));

	nrounds = rijndaelSetupEncrypt(rk, key, 256);

	unsigned char plaintext[16];
	unsigned char ciphertext[16];
	int rlen= 0;
	while (!src.atEnd())
	{
		rlen= src.read((char*)plaintext, 16);
		if (rlen <= 0) break;
		for (int j=rlen; j < 16; j++) plaintext[j] = ' ';
		rijndaelEncrypt(rk, nrounds, plaintext, ciphertext);
		if(dst.write((const char*)ciphertext,16) == -1)
		{
			src.close();
			dst.close();
			qCritical()<<"Can't write to file!";
			return 1;
		}
	}
	src.close();
	dst.close();
	return 0;
}
